function iscp_ready(wx_code) {
	if (isFlag) {
		// 开发模式直接跳过
		let data = {
			CODE: wx_code,
			appId: "a5edcee2ff464051a22a2133bc4d1485"
		}
		data = JSON.stringify(data);
		$.ajax({
			url: "https://jtigw.isgcc.net:10443/igwmobile/proxy/getUserByIgwCode",
			type: "post",
			// async: true, //是否同步，false表示同步请求
			dataType: "json",
			data: data,
			headers: {
				"Content-Type": "application/json;charset=UTF-8",
			},
			success: function (res, txt, xhr) {
				if (res.code == "100001") {
					getAuthentication(res.data)
				} else {
					$("#showP").html("登录失败," + "用户信息获取为空")
				}
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				$("#showP").html("登录失败," + "用户信息获取为空")
			}
		})
	} else {
		// 生产模式 需要text.js 中的iscp
		// 微信注册
			login_ready(wx_code);
			setTimeout(() => {
				iscpInit(function (err) {
					if (!err)
						sessionStorage.getItem("auth_data") && getAuthentication(sessionStorage.getItem("auth_data"));
				})
			})
		3
	}
	}
	// 初始化
function iscpInit() {
    wx.invoke("ext_ISCP_Init", {
        data: {
            iscpIP: magentid
        }
    }, function(res) {
        if (res.err_msg.substr(res.err_msg.lastIndexOf(":")) === ":ok") {
            $("#showP").html("建立安全连接初始化成功")
            iscpConnection()
        } else {
            $("#showP").html("建立安全连接初始化失败")
        }
    });
}
// 建立连接
function iscpConnection() {
    console.log("iscpConnection start");
    wx.invoke("ext_ISCP_ConnectService", {
        data: {
            iscpIP: magentid,
            ip: urlLinkIp,
            port: urlLinkPort,
            user: urlServeruser,
            appid: magentid
        }
    }, function(res) {
        if (res.err_msg.substr(res.err_msg.lastIndexOf(":")) === ":ok") {
            $("#showP").html("建立安全连接成功")
            iscpTransferPort()
        } else {
            $("#showP").html("建立安全连接失败")
        }
    });
}

// 获取端口
function iscpTransferPort() {
    wx.invoke("ext_ISCP_GetLocalPort", {
        data: {
            iscpIP: magentid,
            ip: urlLocalip,
            port: urlLocalport
        }
    }, function(res) {
        if (res.err_msg.substr(res.err_msg.lastIndexOf(":")) === ":ok") {
            iscp.port = res.result;
            // sessionStorage.setItem("iscp_port", "18080")
            sessionStorage.setItem("iscp_port", res.result)
			sessionStorage.getItem("auth_data") && getAuthentication(sessionStorage.getItem("auth_data"));
            $("#showP").html("建立安全连接获取端口成功")
                // iscpState()  //感觉没用
            sessionStorage.setItem("err_msg", "err_msg")
        } else {
            $("#showP").html("建立安全连接获取端口失败")
        }
    });
}

function login_ready(wx_code) {
	let data = {
		CODE: wx_code,
		appId: "09bf59bdeb8748d0b647124c420ef9cd" //天津测试环境

	}
	data = JSON.stringify(data);
	$.ajax({
		url: "https://id.sgcc.com.cn:10443/igwmobile/proxy/getUserByIgwCode",
		type: "post",
		// async: true, //是否同步，false表示同步请求
		dataType: "json",
		data: data,
		headers: {
			"Content-Type": "application/json;charset=UTF-8",
		},
		success: function (res, txt, xhr) {
			if (res.code == "100001") {
				sessionStorage.setItem("auth_data", res.data)
				sessionStorage.getItem("iscp_port") && getAuthentication(res.data)
			} else {
				$("#showP").html("登录失败," + "用户信息获取为空")
			}
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			$("#showP").html("登录失败," + "用户信息获取为空")
		}
	})
} 
let loginNum = 0
// 获取个人信息   请求头
function getAuthentication(data) {
	$("#showP").html("正在登录...")
	if(loginNum > 1) {
		return
	}
	loginNum ++
	const {
		publicKey,
		privateKey
	} = sm2.generateKeyPairHex();
	sessionStorage.setItem("fpuk", publicKey)
	sessionStorage.setItem("fprk", privateKey)
	if (sessionStorage.getItem("iscp_port")) {
		iscp_port = sessionStorage.getItem("iscp_port");
	} else {
		iscp_port = ""
	}
	let timestamp = Date.now() + "";
	let pppp = {
		"code": data,
		"ticketId":titcketId,
		"time": timestamp
	}
	pppp = JSON.stringify(pppp)
	let dddd = sm3(pppp)
	let fpuk = sessionStorage.getItem("fpuk")
	$.ajax({
		url: localUrlLink + iscp_port + "/tjAiAssistant/isc/acceptParam",
		type: "post",
		async: true, //是否同步，false表示同步请求
		dataType: "json",
		// contentType: 'application/x-www-form-urlencoded',
		data: pppp,
		headers: {
			sign: dddd,
			fpuk: fpuk
		},
		success: function (res, txt, xhr) {
			let Authentication = xhr.getResponseHeader("Authentication")
			let bpuk = xhr.getResponseHeader("bpuk")
			if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
				if (Authentication && bpuk) {
					if (res.code == 200) {
						$("#showP").html("登录成功")
						sessionStorage.setItem("Authentication", Authentication);
						const {
							userId,
							email,
							unitId,
							name,
							menus
						} = res.resultValue;
						sessionStorage.setItem("Authentication", Authentication);
						sessionStorage.setItem("userId", userId);
						sessionStorage.setItem("toMail", email);
						sessionStorage.setItem("unitId", unitId);
						sessionStorage.setItem("bpuk", bpuk);
						sessionStorage.setItem("userName", name);
						sessionStorage.setItem("newMenus", JSON.stringify(menus));
						const newArr = menus.filter(item => item.id != 12);
						sessionStorage.setItem("menus", JSON.stringify(newArr));
						if (sessionStorage.getItem("userId") && sessionStorage.getItem("userName") && sessionStorage.getItem("Authentication")) {
							const redirectUrl = sessionStorage.getItem("search") || "./common/Home.html";
                            $(location).attr("href", redirectUrl);
							// if (sessionStorage.getItem("search")) {
							// 	$(location).attr("href", sessionStorage.getItem("search"));
							// } else {
							// 	$(location).attr("href", "./common/Home.html");
							// }
						}
					
					} else if (res.code == 500) {
						$("#showP").html("登录失败," + res.resultValueStr)
					} else {
						$("#showP").html("登录失败," + res.resultValueStr)
					}
				} else {
					$("#showP").html("登录失败," + res.resultValueStr)
				}

			} else {
				$("#showP").html("登录失败, 完整性校验失败！")
			}
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			$("#showP").html("登录请求失败")
		}
	});
}
